package com.pactera.demo.security.handler;

import com.pactera.demo.common.dto.ResponseResult;
import com.pactera.demo.common.enums.StatusCodeEnum;
import com.pactera.demo.common.exception.ResourceNotFoundException;
import com.pactera.demo.common.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 自定义防问被拒绝的处理器
 * </p>
 *
 * @author chang.zhou
 * @version 1
 * @date Created in 2020/2/28 17:46
 */
@Slf4j
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
            throws IOException, ServletException {

        log.info("SimpleAccessDeniedHandler -> AccessDeniedException -> {}", accessDeniedException.getClass().getName());

        ResponseResult responseResult = null;
        if(accessDeniedException instanceof ResourceNotFoundException){
            responseResult = ResponseResult.fail(StatusCodeEnum.RESOURCE_NOT_FOUND);
        }else{
            responseResult = ResponseResult.fail(StatusCodeEnum.UNAUTHENTICATED_ACTION);
        }

        ResponseUtil.jsonWriter(response,responseResult);
    }
}
